$(function () {
	$('.reg-link').on('click', function () {
		$('.login').hide();
		$('.reg').show();
	});

	$('.login-link').on('click', function () {
		$('.login').show();
		$('.reg').hide();
	});

	let form = layui.form;
	form.verify({
		username: (value, item) => { // value：表单的值、item：表单的DOM对象
			if (!new RegExp('^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$').test(value)) {
				return '用户名不能有特殊字符';
			}
			if (/(^\_)|(\__)|(\_+$)/.test(value)) {
				return '用户名首尾不能出现下划线\'_\'';
			}
			// if (/^\d+\d+\d$/.test(value)) {
			// 	return '用户名不能全为数字';
			// }
		},
		pwd: [/^[\S]{6,12}$/, '密码必须6到12位,且不能出现空格'],
		repwd: value => {
			let pwd = $('.reg .layui-input[name="password"]').val();
			if (pwd !== value) return '两次密码不一致';
		}
	});

	$('.form-reg').on('submit', function (e) {
		e.preventDefault();
		let username = $('.form-reg [name="username"]').val();
		let password = $('.form-reg [name="password"]').val();
		$.post('/api/reguser', { username: username, password: password }, res => {
			if (res.status !== 0) return layer.msg(res.message);
			layer.msg('注册成功, 请登录! ');
			$('.login-link').click();
		});
	});

	$('.form-login').on('submit', function (e) {
		e.preventDefault();
		let data = $(this).serialize();
		$.post('/api/login', data, res => {
			if (res.status !== 0) return layer.msg(res.message);
			layer.msg('登录成功! ');
			localStorage.setItem('token', res.token);
			location.href = '/index.html';
		});
	});
});
